//
//  AppDelegate.m
//  MDC
//
//  Created by Kang on 16/9/6.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "AppDelegate.h"
#import "SearchVC.h"
#import "WelcomeViewController.h"
#import "JPUSHService.h"
#import "TabBarC.h"
#import <AdSupport/AdSupport.h>
#import "JPUSH.h"
#import <CoreData/CoreData.h>
#import <CommonCrypto/CommonDigest.h>


#define SUPPORT_IOS8 1
#define _IPHONE80_ 80000

@interface AppDelegate () <UIAlertViewDelegate> {
    BOOL isJudge; //判断跳转
    TabBarC *MDC_tabBarC;
    int i;
}

@property (strong, nonatomic)JPUSH *jp;
@end

@implementation AppDelegate

//static SystemSoundID shake_sound_male_id = 0;

- (id)init
{
    if (self = [super init]) {
        _isLaunchedByNotification = NO;
        //测试用
        isJudge = YES;
    }
    return self;
}

#pragma mark - application 首次运行
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
     //捕捉异常
    //  NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
    // 初始化 icon
    [NSUD setObject:@(0) forKey:@"applicationIconBadgeNumber"];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    [self loadWindow]; //创建窗口
    
    // Mob SMS
    [SMSSDK registerApp:MOBSMSAPPKEY withSecret:MOBSMSAPPSECRET];
    // Code Data
    [self setManagedObjectContext:self.managedObjectContext];
    //注册极光推送
    [self.jp registerPushServiceWithApplication:application :launchOptions];

    
    return YES;
    
}




#pragma mark - 程序暂行
- (void)applicationWillResignActive:(UIApplication*)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

#pragma mark - 程序进入后台
- (void)applicationDidEnterBackground:(UIApplication*)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    //  UIBackgroundTaskIdentifier task = [application beginBackgroundTaskWithExpirationHandler:^{
    // 当申请的后台运行时间已经结束，会调用这个block;
    // SearchVC *sear =[SearchVC sharedSearchVC];
    //  sear.navigationController.tabBarItem.badgeValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"BadgeNumber"];
    
    //  任务结束
    //        [application endBackgroundTask:task];
    //
    //    }];
    
//    [[NSNotificationCenter defaultCenter] removeObserver:[JPUSH sharedJPUSH] name:kJPFNetworkDidReceiveMessageNotification object:nil];
    

    
//    [[JPUSH sharedJPUSH] Deleteaccount];
}


#pragma mark - 程序进入前台
- (void)applicationWillEnterForeground:(UIApplication*)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
//    [[JPUSH sharedJPUSH] registerMsgReceive];
    
    
//    [[JPUSH sharedJPUSH] albbBindChannel];
    
    
}




#pragma mark - 程序重新激活
- (void)applicationDidBecomeActive:(UIApplication*)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

  

}

#pragma mark - 程序意外终止
- (void)applicationWillTerminate:(UIApplication*)application
{
    // 当应用程序即将终止时调用。如果适当的话，保存数据。 See also applicationDidEnterBackground:.
    // 配合Core Data 使用
    
    [self saveContext]; //应用程序的托管对象上下文中的更改。
}


- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
    //极光推送获取deviceToken
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [JPUSHService registerDeviceToken:deviceToken];
    [NSUD setObject:deviceToken forKey:@"YTYanK"];
    
}



#pragma mark -  此方法是IOS7.0之前的版本使用的推送   -用户点击了通知，应用在前台 或者开启后台并且应用在后台 时调起
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(nonnull NSDictionary*)userInfo {
    //极光推送接收通知
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"收到通知:%@", [self logDic:userInfo]);
    
}

#pragma mark -  此方法是IOS7.0之后的版本使用的推送   -用户点击了通知，应用在前台 或者开启后台并且应用在后台 时调起
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(nonnull NSDictionary*)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler {
   
    //极光推送接收通知
    [JPUSHService handleRemoteNotification:userInfo];
    
    
    NSLog(@"推送字典 ====== %@",userInfo);
    
 
    
    
    NSNotification* notif = [NSNotification notificationWithName:BADGE_Num object:self userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notif];
    completionHandler(UIBackgroundFetchResultNewData);
    
}


// 当 DeviceToken 获取失败时，系统会回调此方法
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
    NSLog(@"----->DeviceToken 获取失败，原因：%@", error);
}


#pragma mark - 加载root 窗口
- (void)loadWindow {
    
    UIStoryboard *main;
    //    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"isHaveVisit"]) {
    // 判断登陆令牌是否为空
    NSLog(@"%@",[NSUD objectForKey:@"token"]);
    if (isLogin) { // - YES不是空
        main = [UIStoryboard storyboardWithName:@"Main" bundle:NULL];
        MDC_tabBarC = [main instantiateInitialViewController];
        [UIApplication sharedApplication].statusBarHidden = NO;
        self.window.rootViewController = MDC_tabBarC;
        [self.jp updateSession];
        
        self.jp.sonWindow = self.window;
        self.jp.tabBarC = MDC_tabBarC;
        
        NSLog(@"%d---->",[[NSUD objectForKey:MDC_SET_MASKDATAVIEW] intValue]);
        
        if ([[NSUD  objectForKey:MDC_SET_MASKDATAVIEW] intValue] != 0 ) {
            NavigationC *navigationCont = (NavigationC *)MDC_tabBarC.viewControllers[0];//1
            SearchVC * search = navigationCont.viewControllers[0];
            if(navigationCont.viewControllers.count > 1) {
                [navigationCont popToRootViewControllerAnimated:YES];
            }
        }
    }else { // - 空
        main = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
        self.window.rootViewController = [main instantiateInitialViewController];
    }
    
    //    }else{
    //        //没有进入过APP,加载欢迎页
    //        [NSUD setObject:@"重新安装APP了" forKey:MDC_SET_COURSE_STATS];
    //        WelcomeViewController *welcome = [[WelcomeViewController alloc]init];
    //        welcome.rootWindow = self.window;
    //        self.window.rootViewController = welcome;
    //    }

}



//===============================极光推送=============================================
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
// 在 iOS8 系统中，还需要添加这个方法。通过新的 API 注册推送服务
- (void)application:(UIApplication*)application didRegisterUserNotificationSettings:(UIUserNotificationSettings*)notificationSettings {
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerForRemoteNotifications)]) {
        [application registerForRemoteNotifications];
    }
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forLocalNotification:(UILocalNotification *)notification
  completionHandler:(void (^)())completionHandler {
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forRemoteNotification:(NSDictionary *)userInfo
  completionHandler:(void (^)())completionHandler {
}
#endif

#pragma mark -  此方法本地的推送
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    
    NSLog(@"接收本地通知啦！！！----》%@", [notification userInfo]);
   /* TabBarC *tabbarCont = (TabBarC *)self.window.rootViewController;
    NavigationC *navigationCont = (NavigationC *)tabbarCont.viewControllers[0];
    SearchVC * search = navigationCont.viewControllers[0];
   
    
    if (isJudge == YES) {
        //    NSNotification* notif = [NSNotification notificationWithName:BADGE_Num object:self userInfo:[notification userInfo]];
        //    [[NSNotificationCenter defaultCenter] postNotification:notif];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
        }];
        
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication]  cancelLocalNotification:notification];
            
            
            [navigationCont popToRootViewControllerAnimated:YES];
            navigationCont.tabBarController.selectedIndex = 0;
            NSLog(@"%@--->%@",navigationCont.viewControllers, [notification userInfo]);
            [search JumpWithVlue:[notification userInfo]];
            
        }];
        [search addUnreadCount:[notification userInfo]];
        
        //        MDC_alert =  [UtilToolsClss addViewController:self.window.rootViewController withTitleStr:nil withMessage:[[[notification userInfo] objectForKey:@"aps"] objectForKey:@"alert"] withAction:action withOKAction:okAction withStyle:UIAlertControllerStyleAlert];
        //        [self.window.rootViewController presentViewController:MDC_alert animated:YES completion:nil];
        
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        isJudge = NO;
    }else {
        if ([notification userInfo] != nil) {
            [navigationCont popToRootViewControllerAnimated:YES];
            navigationCont.tabBarController.selectedIndex = 0;
            NSLog(@"%@--->%@",navigationCont.viewControllers, [notification userInfo]);
            [search JumpWithVlue:[notification userInfo]];
        }
    }
    */
    
}


// log NSSet with UTF8
// if not ,log will be \Uxxx
- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str = [NSPropertyListSerialization propertyListWithData:tempData options:NSPropertyListImmutable format:NULL error:NULL];
    
    return str;
}

//=====================================极光推送======================================

- (UIWindow *)window {
    if (!_window) {
        _window = [[UIWindow alloc] init];
        _window.frame = [UIScreen mainScreen].bounds;
        [_window makeKeyAndVisible];
    }
    return _window;
}

//极光推送
- (JPUSH *)jp{
    if (!_jp) {
        _jp = [[JPUSH alloc]init];
    }
    return _jp;
}

/* --------------------------------------------------------------Core Data Stack--------------------------------------------------------------------------*/
#pragma mark - Core Data stack
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "pp.MyCDDemo" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"FiltrationSystem" withExtension:@"momd"];
    NSLog(@"------>>%@",modelURL);
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"FiltrationSystem.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}
- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}


#pragma mark - Core Data Saving support
- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

- (void)setManagedObjectContext:(NSManagedObjectContext*)managedObjectContext
{
    _managedObjectContext = managedObjectContext;
    NSDictionary* info = self.managedObjectContext ? @{ DatabaseAvailabilityContext : self.managedObjectContext } : nil;
    [[NSNotificationCenter defaultCenter] postNotificationName:DatabaseAvailabilityNotification object:self userInfo:info];
}




@end

